package cn.hp.crm.servlet.user;


import cn.hp.crm.service.UserService;
import cn.hp.crm.service.impl.UserServiceImpl;
import cn.hp.crm.util.Constant;
import cn.hp.crm.util.JsonForServlet;
import cn.hp.crm.util.ResultData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/userLogin.do")
public class LoginServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();

    //编写登录的请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        从请求中获取用户提交的数据
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");

//       验证用户输入的验证码
        if (checkCode.equals(req.getSession().getAttribute("checkCode"))){
//            输入正确验证码,进行账号密码验证  基于service层
            boolean flag = userService.login(userName,password);
            if (flag){
//                登录成功时，将用户信息保存在session中
                req.getSession().setAttribute("user",userName);
                JsonForServlet.transferData(resp,ResultData.getSuccess(Constant.LOGIN_SUCCESS_MSG));
            }else {
                JsonForServlet.transferData(resp,ResultData.getFail(Constant.LOGIN_FAIL_MSG));
            }
        }else {
            JsonForServlet.transferData(resp,ResultData.getFail(Constant.CHECK_FAIL_MSG));
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
